<template>
  <div class="app-container">
    <div class="filter-container">
      <el-cascader :options="options" :show-all-levels="false" v-model="listQuery.lineNo" placeholder="请选择产线" :props="{value:'key'}"
       style="width: 200px;" class="filter-item" clearable></el-cascader>
      <el-date-picker
        v-model="listQuery.startTime"
        type="datetime"
        placeholder="请输入开始时间" class="filter-item">
      </el-date-picker>
      <el-date-picker
        v-model="listQuery.endTime"
        type="datetime"
        placeholder="请输入结束时间" class="filter-item">
      </el-date-picker>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves class="filter-item" type="info" icon="el-icon-refresh" @click="handleReset">
        重置
      </el-button>
    </div>
    <el-row style="margin-bottom: 5px;text-align: right">
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleDownload">
        导出
      </el-button>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="工厂" prop="plantNameC" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.plantNameC }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车间" prop="workshopNameC" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.workshopNameC }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产线" prop="lineNameC" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lineNameC }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" prop="startTime" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" prop="endTIme" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="持续时间" prop="delay" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.delay | timeDelayFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column label="停线原因" prop="breakReason" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.breakReason }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>
<script>
import { fetchList, fetchLineList, fetchWorkshopList } from '@/api/bdc/line-stop-query'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { geneTreeData } from '@/utils/tree-gene'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import axios from "axios";
export default {
  name: 'LineStopQuery',
  directives: { waves },
  components: { Pagination },
  filters: {
    // 格式化持续时间显示
    timeDelayFormat(time) {
      const hours = parseInt(time / (60 * 60))
      const minutes = parseInt((time %  (60 * 60)) / 60)
      const seconds = time %  60
      if(hours === 0) {
        if(minutes === 0) {
          return seconds + '秒'
        } else {
          return minutes + '分' + seconds + '秒'
        }
      } else {
        return hours + '时' +  minutes + '分' + seconds + '秒'
      }
    }
  },
  data() {
    return {
      // 查询模块
      options: [],
      originLineData: [],
      listQuery: {
        page: 1,
        limit: 10,
        lineNo: undefined,
        startTime: null,
        endTime: null
      },
      // 导出excel
      downloadLoading: false,
      filename: '产线停线记录' + new Date().valueOf(),
      autoWidth: true,
      bookType: 'xlsx',
      // 表格显示
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
    }
  },
  created() {
    // 获取产线车间数据，生成级联列表
    axios.all([fetchWorkshopList(), fetchLineList()]).then(
        axios.spread((res1, res2) => {
          const workshopList = res1.data.list
          const lineList = res2.data.list
          // 产线数据
          this.originLineData = res2.data.list
          // 初始根节点（必须，用于递归）
          const root = {
            id: workshopList[0].tmBasPlantId,
            parentId: 'root',
            menuName: '根节点'
          }
          // {list: dataArray,key: 'key', parentKey: 'parentId', nameKey: 'menuName'}数据格式
          const list0 = {list: [root], key: 'id', parentKey: 'parentId', nameKey: 'menuName'}
          const list1 = {list: workshopList, key: 'tmBasWorkshopId', parentKey: 'tmBasPlantId', nameKey: 'workshopNameC'}
          const list2 = {list: lineList, key: 'tmBasLineId', parentKey: 'tmBasWorkshopId', nameKey: 'lineNameC'}
          const list = [list0, list1, list2]
          this.options = geneTreeData(list)[0].children
          // console.log(this.originLineData)
        })
      );
    // this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      // 格式化提交数据
      const data = Object.assign({}, this.listQuery)
      if(data.lineNo && data.lineNo.length > 0) {
        const lineId =  data.lineNo[1]
        data.lineNo = this.originLineData.find(a => a.tmBasLineId === lineId).lineNo
      } else {
        data.lineNo = undefined
      }
      if(data.startTime) data.startTime = parseTime(this.listQuery.startTime, '{y}-{m}-{d} {h}:{i}')
      if(data.endTime) data.endTime = parseTime(this.listQuery.endTime, '{y}-{m}-{d} {h}:{i}')
      // 故障状态
      data.status = 'STANDBY'
      
      fetchList(data).then(res => {
        if (res.code == 200) {
          this.list = res.data.list
          // console.log(this.list)
          this.total = res.data.total
        } else {
          this.$message.error('服务器内部错误！');
        }
        this.listLoading = false
      })
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: 10,
        lineNo: undefined,
        startTime: null,
        endTime: null
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['工厂', '车间', '产线', '开始时间', '结束时间', '停线时间', '停线原因']
        const filterVal = ['plantNameC', 'workshopNameC', 'lineNameC', 'startTime', 'endTime', 'delay', 'breakReason']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>